﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace UFODefense
{
    class Missile : DrawableGameComponent
    {
        SpriteBatch m_spriteBatch;
        ContentManager m_contentManager;
        Texture2D m_texture;

        bool m_timeSet;
        //the only time-variable in seconds, allows for slow acceleration over first second etc
        float m_launchTime;
        Vector2 m_position;
        Rectangle m_missRect;

        public Missile(Game game, SpriteBatch SB, ContentManager CM, int Xpos)
            : base(game)
        {
            m_spriteBatch = SB;
            m_contentManager = CM;
            m_position.X = Xpos;
            Game.Components.Add(this);
        }

        public override void Initialize()
        {
            m_position.Y = Definitions.GROUND_Y;
            m_timeSet = false;
            base.Initialize();
            m_missRect.Width = m_texture.Width;
            m_missRect.Height = m_texture.Height;
        }
        protected override void LoadContent()
        {
            m_texture = m_contentManager.Load<Texture2D>("GFX/missile1");

            base.LoadContent();
        }
        /// <summary>
        /// Move missile upwards, check for collision with UFO's or user input for exploding the missile
        /// </summary>
        /// <param name="gameTime"></param>
        public override void Update(GameTime gameTime)
        {
            //set the launch time on the first update
            if (!m_timeSet)
            {
                m_launchTime = gameTime.TotalGameTime.Seconds;
                m_timeSet = true;
            }
            //move Missile upwards
            m_position.Y -= (float)(Definitions.MISSILE_BASE_SPEED * (gameTime.TotalGameTime.TotalSeconds - m_launchTime));
            //calculate the location rectangle for the missile
            m_missRect.X = (int)(m_position.X - (m_texture.Width / 2));
            m_missRect.Y = (int)(m_position.Y - (m_texture.Height / 2));

            //check for collision with UFOs
            if (UFOCollisionObserver.Instance.Notify(m_missRect))
            {
                //TODO: create explosion
                Enabled = false;
                Visible = false;
            }

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
     

            //calculate which missile sprite to use and choose texture accordingly
            m_spriteBatch.Draw(m_texture, m_missRect, Color.White);

            base.Draw(gameTime);
        }
    }
}
